package com.tabuleiro.web.services;

import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Session;

import com.tabuleiro.dominio.Usuario;
import com.tabuleiro.dominio.UsuarioBasico;
import com.tabuleiro.negocio.base.QueryParameters;
import com.tabuleiro.negocio.comum.UsuarioService;
import com.tabuleiro.web.security.AuthenticationException;

/**
 * Basic Security Realm implementation
 * 
 * @author Pablo
 */
public class BasicAuthenticator implements Authenticator
{

    public static final String AUTH_TOKEN = "authToken";

    @Inject
    private UsuarioService usuarioService;

    @Inject
    private Request request;

    public void login(String username, String password) throws AuthenticationException
    {

        UsuarioBasico usuario = usuarioService.findUniqueWithNamedQuery(Usuario.BY_CREDENTIALS, QueryParameters.with(
                "username",
                username).and("password", password).parameters());

        if (usuario == null) { throw new AuthenticationException("The user doesn't exist"); }

        request.getSession(true).setAttribute(AUTH_TOKEN, usuario);
    }

    public boolean isLogado()
    {
        Session session = request.getSession(false);
        if (session != null) { return session.getAttribute(AUTH_TOKEN) != null; }
        return false;
    }

    public void logout()
    {
        Session session = request.getSession(false);
        if (session != null)
        {
            session.setAttribute(AUTH_TOKEN, null);
            session.invalidate();
        }
    }

    public UsuarioBasico getUsuarioLogado()
    {
    	UsuarioBasico usuario = null;

        if (isLogado()) {
            usuario = (UsuarioBasico) request.getSession(true).getAttribute(AUTH_TOKEN);
        }
        else {
            throw new IllegalStateException("The user is not logged ! ");
        }
        return usuario;
    }

}
